|
|
|
|
|
|
|
Creating a Wrapper Function |
|
|
|
|
|
|
|
|
Often programmers create a "wrapper" function around one or more Windows API calls. A wrapper function is a standard VB function that handles calls between the rest of your program and the API function. Although using this type of function sounds like an extra step, one of its purposes is actually to eliminate extra steps associated with calling the API function. For example, suppose you are writing an installation program and need to check for the amount of free storage space on a given disk drive. The Windows API function GetDiskFreeSpace returns free space information, but not in the exact format you need. A simple user-defined function such as dblFreeByes, shown in Listing 20.1, calls the API but returns only the required information. |
|
|
|
|
|
|
|
|
Listing 20.1 APIWRAP.ZIPThe Wrapper Function Returns Only the Information Needed by the Rest of the Program |
|
|
|
|
|
|
|
|
Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA" _
(ByVal lpRootPathName As String, lpSectorsPerCluster As Long, _
lpBytesPerSector As Long, lpNumberOfFreeClusters As Long, _
lpTtoalNumberOfClusters As Long) As Long
Function dblFreeBytes(sPath As String) As Double
Dim sDrive As String
Dim lReturn As Long
Dim l1 As Long 'l1 = Sectors Per Cluster
Dim l2 As Long 'l2 = Bytes Per Sector
Dim l3 As Long 'l3 = Number Of Free Clusters
Dim l4 As Long 'l4 = Total Number Of Clusters
sDrive = Left$(sPath, 1) & ":\" 'Get drive letter from path
lReturn = GetDiskFreeSpace(sDrive, l1, l2, l3, l4)
dblFreeBytes = l1 * l2 * l3
End Function |
|
|
|
|
|
|
|
|
As you can see from the preceding listing, GetDiskFreeSpace actually returns four values. If you called this function directly several times throughout your program, you would have to add four Dim statements and know the purpose of each parameter. However, using dblFreeBytes, which automates the mundane work of the API call for you, is much easier: |
|
|
|
|
|
|
|
|
If dblFreeBytes(app.path) < REQUIRED_BYTES Then
Msgbox "Error: Not Enough Disk Space!"
End If |
|
|
|
|
|
|
|
|
Wrapper functions can also be used to eliminate the extra string manipulation required by many API functions. Typically, API functions that modify a string passed to them require you to supply the length of the string and fill the string with spaces. An example of using a wrapper function to get around this step is demonstrated in Chapter 21, "Working with Files." |
|
|
|
|
|
|
|
|
See "Using INI Files in Visual Basic," p. 485 |
|
|
|
|
|